<template>
  <div class="search-container">
    <!-- 顶部搜索栏 -->
    <form class="search-form" action="/">
      <van-search
        v-model.trim="searchText"
        show-action
        background="#2892ff"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
        autofocus
      />
    </form>
    <!-- /顶部搜索栏 -->
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :searchText="searchText" />
    <!-- /搜索结果 -->
    <!-- 搜索联想 -->
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    />
    <!-- /搜索联想 -->
    <!-- 历史记录 -->
    <search-history
      v-else
      @search="onSearch"
      :searchHistory="searchHistory"
      @clear-search-history="searchHistory = []"
    />
    <!-- /历史记录 -->
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
// import { setItem, getItem } from '@/store/storage'
// 取别名引入所有 别名 加 点 调用 stores.setItem() stores.getItem()
import * as stores from '@/store/storage'
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  props: {},
  data() {
    return {
      searchText: '',
      isResultShow: false,
      // searchHistory: getItem('TOUTIAO_SEARCH_HISTORY') || [], // 搜索结果
      searchHistory: stores.getItem('TOUTIAO_SEARCH_HISTORY') || [] // 搜索结果
    }
  },
  computed: {},
  watch: {
    searchHistory() {
      console.log('搜索记录变化了')
      // setItem('TOUTIAO_SEARCH_HISTORY', this.searchHistory)
      stores.setItem('TOUTIAO_SEARCH_HISTORY', this.searchHistory)
    }
  },
  created() {},
  mounted() {},
  methods: {
    onSearch(val) {
      if (!val.trim()) {
        return this.$toast('不能为空')
      }
      //   console.log(str)
      // 更新文本框
      this.searchText = val
      // 将文本添加到搜索记录数组中
      // 不能有重复结果，最新在前面
      // indexOf(val) 查找 val 对应的索引，找到返回索引号，找不到返回-1
      const index = this.searchHistory.indexOf(val)
      if (index !== -1) {
        // 原数组中已存在，删除
        this.searchHistory.splice(index, 1)
      }
      // 搜索的文本添加到第一个位置 unshift(val)
      this.searchHistory.unshift(val)
      // 判断数组的长度，要求历史记录不能大于5条
      // 长度为 0 时，数组将置空
      if (this.searchHistory.length > 5) {
        this.searchHistory.length = 5
      }
      // 显示搜索结果
      this.isResultShow = true
    },
    onCancel() {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
